<?php
require_once "./connect_db.php";

set_time_limit( 0 );
ob_implicit_flush();

$num=0;
$flag=0;

$socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
if ( $socket === false )
{
	echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "<br/>";
}
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1))
{
	echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}
$ok = socket_bind( $socket, '10.133.194.44', 8080 );
if ( $ok === false )
{
	echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) );
}

while(true)
{
	$ip;
	$port;
	$buf="";
	if(socket_recvfrom( $socket, $buf,1024, 0, $ip, $port )>0)
	{
		date_default_timezone_set('PRC');
		$d=date('y-m-d h:i:s',time());
		$dd=time();
		$t=time();
		// echo $d;die;

		$chip=explode(',', $buf);		//分解信息
		/**
		 * 验证信息是否为空
		 */
		if($chip[0]=='' || $chip[1]=='' || $chip[2]==''){
			echo "非法添加设备";exit();
		}
		// print_r($chip);die;

		//根据表中信息有无对send_info进行操作
		$sql0="SELECT * FROM send_info WHERE chipId='$chip[0]'";
		$chip1=mysql_query($sql0);
		$chip1Num=mysql_num_rows($chip1);
		// echo $chip1Num;die;
		if($chip1Num){		//查询到该设备信息，更新
			$sql1="UPDATE send_info SET isOnLine='$dd',date='$d',deviceIp='$ip',devicePort='$port',deviceState='$chip[2]' WHERE chipId='$chip[0]'";
			//$query = "UPDATE Employee SET name='$name', price='$price' WHERE ID='$rowID'";
      		mysql_query($sql1);

			echo "update";
		}else{		//发送表中无该设备信息，插入
			$sql2="INSERT INTO send_info(chipId,date,deviceIp,devicePort,deviceType,deviceState,isOnLine) VALUES('$chip[0]','$d','$ip','$port','$chip[1]','$chip[2]','$dd')";
			mysql_query($sql2);
			echo "insert";
		}
		
		$sql10="SELECT id FROM send_info WHERE chipId='$chip[0]'";
		$chip10=mysql_query($sql10);
		$result_arr=mysql_fetch_assoc($chip10);
		$idd = $result_arr["id"];
		//数据插入return_info表
		$sql3="INSERT INTO return_info(time,ip,port,chipId,deviceState,deviceType,deviceId) VALUES('$t','$ip','$port','$chip[0]','$chip[2]','$chip[1]','$idd')";
		mysql_query($sql3);

//		$mess=$idd." ".$d."  ".$chip[0]."  ".$chip[1]."  ".$chip[2]." ".$port . "  " . $ip."  \r\n";
//
//		$fp = fopen("a.txt", "a") or die("Unable to open file!111".$mess);
////			  $fp = fopen("client.txt", "w");
//		fwrite($fp,$mess);
//		fclose($fp);
		// echo "succeed\n";
	}
}
?>


